<?php
/**
 * User: b179a9
 * Date: 9/26/11
 * Time: 6:06 PM
 */

class App_Form_News_Form extends Zend_Form
{


    function init()
    {

        $this->setMethod('post');
        $this->setAction('');
        $this->setAttrib('enctype', 'multipart/form-data');

        $id = new Zend_Form_Element_Hidden('id');
        $this->addElement($id);

        $title = new Zend_Form_Element_Text('title');
        $title->setLabel('Title:')
                ->setRequired()
                ->addValidators(array(new Zend_Validate_StringLength(1, 64)));
        $this->addElement($title);

        $content = new Zend_Form_Element_Textarea('content');
        $content->setLabel('Content:')
                ->setRequired();
        $this->addElement($content);

        $date = new Zend_Form_Element_Text('publishDate');
        $date->setLabel('Publish date:')
            ->addValidator(new Zend_Validate_Date())
            ->setAttrib('class', 'datepicker');
        $this->addElement($date);

        $rubricsManager = new \Managers\Rubrics();
        $rubrics = $rubricsManager->getList(\Managers\Rubrics::UNLIMITED);

        $rubric_element = new Zend_Form_Element_Select('rubric');
        $rubric_element->setRequired()
            ->setLabel('Rubric:');
        foreach($rubrics as $rubric) {
            $rubric_element->addMultiOption($rubric['id'], $rubric['name']);
        }
        $this->addElement($rubric_element);

        $tags = new Zend_Form_Element_Select('tags');
        $tags->setAttrib('id', 'tags')
            ->setLabel('Tags:')
            ->setRegisterInArrayValidator(false);
        $this->addElement($tags);


        $img = new Zend_Form_Element_File('img');
        $img->setLabel('Image:')
                ->setDestination(dirname(APPLICATION_PATH) . '/public/images/news/');
        $this->addElement($img);

        $public = new Zend_Form_Element_Checkbox('public');
        $public->setLabel('Public:');
        $this->addElement($public);

        $top = new Zend_Form_Element_Checkbox('top');
        $top->setLabel('In top:');
        $this->addElement($top);

        $submit = new Zend_Form_Element_Submit('submit');
        $submit->setLabel('Save');

        $this->addElement($submit);

        $this->addElement('hash', 'csrf', array(
            'ignore' => true,
        ));

    }

    public function populate($values) {
        parent::populate($values);

        $tags_elem = $this->getElement('tags');
        $id = $values['id'];
        if(!empty($id)) {
            $newsManager = new \Managers\News();
            $article = $newsManager->getById($id);

            if($article) {
                $tags = $article['tags'];
                foreach($tags as $tag) {
                    $tags_elem->addMultiOption($tag['id'], $tag['name']);
                }
            }

        }
    }
}
